/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BANewsEventsViewController.m
//  redia-bapps-ios
//
//  Created by Mads Darø Kristensen on 10/7/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BANewsEventsViewController.h"
#import "BAFlyoutMenuViewController.h"
#import "BAUtils.h"
#import "BALibrarySettings.h"
#import "BATabSwitchViewController.h"
#import "BANewsTableViewController.h"
#import "BANews.h"
#import "BAEvent.h"
#ifdef BA_IMF_BUILD
#import "IMFRPCManager.h"
#import "IMFSuggestedPackagePageViewController.h"
#endif
#import "BAPatronSettings.h"
#import "BAEventsTableViewController.h"
#import "InfoGalleriImageUrlUtils.h"
#import "LazyLoadManager.h"
#import "BANewsViewController.h"
#import "BAColoredCoverViewController.h"
#import "BAFeaturedNewsPageViewController.h"
#import "BAEventManager.h"
#import "BAEventsCache.h"
#import "BARootViewController.h"

@class IMFSuggestedPackagePageViewController;

@interface BANewsEventsViewController () {
    
    BAColoredCoverViewController* coloredCoverLoadingIndicator;
    BOOL suggestedPackagesLoaded;
    BOOL newsLoaded;
    BOOL eventsLoaded;
    BOOL shouldDisplayFeaturedNews;
}

@property (nonatomic, strong) BANewsTableViewController* newsViewController;
@property (nonatomic, strong) BAEventsTableViewController* eventsViewController;

@property (weak, nonatomic) IBOutlet UIView *tabSwitchView;

@property (weak, nonatomic) IBOutlet UIView *newsContainerView;
@property (weak, nonatomic) IBOutlet UIView *eventsContainerView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *featuredNewsHeight;

@property (nonatomic, strong) BANews* headLineNews;

@property (strong, nonatomic) BAFeaturedNewsPageViewController *featuredPager;
@property (strong, nonatomic) IMFSuggestedPackagePageViewController *suggestedPackagePager;

@property (weak, nonatomic) IBOutlet UIView *topContainerView;

@property (nonatomic, strong) NSArray* featuredNews;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *topFeatureLoadingIndicator;

@end

@implementation BANewsEventsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    BA_FLYOUT_MENU_ADD_BUTTON(BASpecialNavigationBarConfigurationDefault)
  
    BATabSwitchViewController* tabswitch = [[BATabSwitchViewController alloc] initWithSelectionColor:nil unselectionColor:[UIColor colorWithWhite:0.85 alpha:1]];
    [self.tabSwitchView addSubview:tabswitch.view];
    [BAUtils setViewToFillParent:tabswitch.view];
    //[tabswitch.view setFrame:CGRectMake(0, 0, 320, 44)];
    
    [tabswitch setTitleStrings:@[@"NYHEDER",@"ARRANGEMENTER"]];
    [tabswitch setDelegate:self];
    [self addChildViewController:tabswitch];
    
    _newsViewController = [BANewsTableViewController new];
    [self.newsContainerView addSubview:self.newsViewController.view];
    [self addChildViewController:self.newsViewController];
    [BAUtils setViewToFillParent:self.newsViewController.view];
    
    _eventsViewController = [BAEventsTableViewController new];
    [self.eventsContainerView addSubview:self.eventsViewController.view];
    [self addChildViewController:self.eventsViewController];
    [BAUtils setViewToFillParent:self.eventsViewController.view];
    [self.eventsContainerView setHidden:YES];
    
    [self updateContent];

    //if (![[BARootViewController instance] isShowingUserGuide]) {
        coloredCoverLoadingIndicator = [BAColoredCoverViewController new];
        [self.navigationController.view addSubview:coloredCoverLoadingIndicator.view];
    //}
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receivedDidBecomeActiveNotification:)
                                                 name:BA_APP_DELEGATE_DID_BECOME_ACTIVE
                                               object:nil];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self enableUserInteraction];
    [self updateContentIfNeeded];
}

-(void)dealloc{
    [[LazyLoadManager instance] cancelConnectionsForOwner:self];
    [BARPCManager closeConnectionsForView:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_APP_DELEGATE_DID_BECOME_ACTIVE object:nil];
    
}

- (void) receivedDidBecomeActiveNotification:(NSNotification*) notification
{
    [self updateContentIfNeeded];
}

-(void)updateContentIfNeeded
{
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    if (now - [BARPCManager instance].newsLastUpdated > 3600) {
        [self updateContent];
    }
}

-(void)updateContent
{
    if ([BALibrarySettings instance].isImfEnabled) {
        [self updateSuggestedPackages];
        shouldDisplayFeaturedNews = NO;
    } else{
        shouldDisplayFeaturedNews = YES;
        
    }
    [self updateNewsAndArrangementsLists];
    
}

-(void)updateNewsAndArrangementsLists
{
    [BARPCManager loadAllNewsFromView:self
                          resultBlock:^(NSArray *results) {
                              newsLoaded = YES;
                              [self processesNewsElements:results];
                              [self dismissColoredCover];
                              //[self.newsViewController setNewsElements:results];
                          } errorBlock:^(int errorCode, NSString *errorMessage) {
                              DLog(@"ERROR loadAllNewsFromView: %@",errorMessage);
                              newsLoaded = YES;
                              [self.newsViewController setNewsElements:nil];
                              [self dismissColoredCover];
                          }];
    
    [[BAEventsCache instance] getEventsWithResultBlock:^(NSArray *events, NSDictionary* eventsDict) {
        eventsLoaded = YES;
        [self.eventsViewController setEventElements:events];
    } errorBlock:^(int errorCode, NSString *errorMessage) {
        DLog(@"ERROR loadAllEventsFromView: %@",errorMessage);
        eventsLoaded = YES;
        [self.eventsViewController setEventElements:nil];
    }];
    
    //This is no longer needed, as we are now using the EventsCache
//    [BARPCManager loadAllEventsFromView:self
//                            resultBlock:^(NSArray *results) {
//                                eventsLoaded = YES;
//                                [self.eventsViewController setEventElements:results];
//                            } errorBlock:^(int errorCode, NSString *errorMessage) {
//                                DLog(@"ERROR loadAllEventsFromView: %@",errorMessage);
//                                eventsLoaded = YES;
//                                [self.eventsViewController setEventElements:nil];
//                            }];

}

-(void)processesNewsElements:(NSArray*)newsElements{

    NSArray* newsListArray = newsElements;
    
    if (newsElements.count > 0) {
        if (shouldDisplayFeaturedNews) {
            //only remove top news if IMF is not enabled
            NSMutableArray* tempArray = [NSMutableArray arrayWithArray:newsElements];
            [tempArray removeObjectAtIndex:0];
            newsListArray = [NSArray arrayWithArray:tempArray];
        }
    }

    [self.newsViewController setNewsElements:newsListArray];

    _featuredNews = [newsElements subarrayWithRange:NSMakeRange(0, (newsElements.count >= 1 ? 1 : newsElements.count))];
    [self setupFeaturedNews];
}

-(void)setupFeaturedNews{
    if (!shouldDisplayFeaturedNews || !newsLoaded) {
        return;
    }
    [self.topFeatureLoadingIndicator stopAnimating];
    if (self.featuredNews.count > 0) {
        _featuredPager = [BAFeaturedNewsPageViewController new];
        [self.topContainerView addSubview:self.featuredPager.view];
        [self addChildViewController:self.featuredPager];
        [BAUtils setViewToFillParent:self.featuredPager.view];
        
        [self.featuredPager setNewsElements:self.featuredNews];
    } else{
        DLog(@"No suggested packages or featured news!");
        self.featuredNewsHeight.constant = 0;
    }
}

-(void)dismissColoredCover
{
    if (coloredCoverLoadingIndicator==nil) {
        return;
    }
    
    if ([BALibrarySettings instance].isImfEnabled && !suggestedPackagesLoaded) {
        return;
    }
    
    if (!newsLoaded) {
        return;
    }
    
    CGRect animframe = coloredCoverLoadingIndicator.view.frame;
    
    animframe.origin.y -= animframe.size.height;
    
    BOOL isShowingUserGuide = [BARootViewController instance].isShowingUserGuide;
    
    [UIView animateWithDuration:isShowingUserGuide ? 1.0 : 0.5
                     animations:^{
                         if (isShowingUserGuide) {
                             //if userguide present, just fade out
                             coloredCoverLoadingIndicator.view.alpha=0;
                         } else {
                             //otherwise move upwards and out
                             coloredCoverLoadingIndicator.view.frame = animframe;
                         }
                     }
                     completion:^(BOOL finished) {
                         [coloredCoverLoadingIndicator.view removeFromSuperview];
                         coloredCoverLoadingIndicator = nil;
                     }
     ];
}

-(void)updateSuggestedPackages
{
#ifdef BA_IMF_BUILD
    [IMFRPCManager getSuggestedPackagesAsyncFromView:self
                                               count:4
                                      skipPackageIds:@[]
                                              result:^(NSArray* result) {
                                                  if (result.count > 0) {
                                                      if (self.suggestedPackagePager!=nil) {
                                                          [self.suggestedPackagePager.view removeFromSuperview];
                                                          [self.suggestedPackagePager removeFromParentViewController];
                                                          self.suggestedPackagePager = nil;
                                                      }
                                                      [self.topFeatureLoadingIndicator stopAnimating];
                                                      _suggestedPackagePager = [IMFSuggestedPackagePageViewController new];
                                                      [self.suggestedPackagePager.view setFrame:self.topContainerView.bounds];
                                                      [self.topContainerView addSubview:self.suggestedPackagePager.view];
                                                      [self addChildViewController:self.suggestedPackagePager];
                                                      
                                                      //[self setViewToFillParent:self.suggestedPackagePager.view];
                                                      [self.suggestedPackagePager setPackages:result];
                                                  }
                                                  else{
                                                      shouldDisplayFeaturedNews = YES;
                                                      [self setupFeaturedNews];
                                                  }
                                                  
                                                  suggestedPackagesLoaded = YES;
                                                  [self dismissColoredCover];
//                                                  for (IMFPackage* package in result) {
//                                                      DLog(@"got suggested package title: %@",package.title);
//                                                  }
                                                  
                                              } errorBlock:^(int errorCode, NSString *errorMessage) {
                                                  DLog(@"ERROR getSuggestedPackagesAsyncFromView: %@",errorMessage);
                                                  [self dismissColoredCover];
                                                  //TODO
                                              }
     ];
#endif
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Flyout menu

BA_FLYOUT_MENU_ADD_CALLBACK

- (void)enableUserInteraction
{
    self.view.userInteractionEnabled = YES;
    self.tabBarController.tabBar.userInteractionEnabled = YES;
}

- (void)disableUserInteraction
{
    self.view.userInteractionEnabled = NO;
    self.tabBarController.tabBar.userInteractionEnabled = NO;
}

#pragma mark BATabSwitchDelegate

-(void)tabSwitchSelected:(int)index withTitle:(NSString *)title{
    if (index == 0) {
        [self.newsContainerView setHidden:NO];
        [self.eventsContainerView setHidden:YES];
    } else{
        [self.newsContainerView setHidden:YES];
        [self.eventsContainerView setHidden:NO];
    }
}

@end
